package com.hsy.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsy.service.UserService;
import com.hsy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/DeleteUserServlet")
public class DeleteUserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    // 使用doPost方法来处理删除用户请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应的字符编码和内容类型
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取前端传递的userId
        Long userId = Long.valueOf(request.getParameter("userId"));

        // 创建ObjectMapper实例，用于将Map转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> responseData = new HashMap<>();

        // 调用userService的delete方法删除用户
        int result = userService.delete(userId);

        // 根据删除结果构建响应数据
        if (result > 0) {
            responseData.put("success", true);
            responseData.put("message", "删除成功");
        } else {
            responseData.put("success", false);
            responseData.put("message", "删除失败");
        }

        // 将响应数据转换为JSON字符串
        String responseJson = objectMapper.writeValueAsString(responseData);

        // 通过PrintWriter将JSON格式的响应数据写回给前端
        PrintWriter writer = response.getWriter();
        writer.write(responseJson);
        writer.flush();
        writer.close();
    }
}
